import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Scanner;

class ReceivingThread extends Thread 
   {
	   private Socket sock;
	   private MDUser mdUser;
	   public ReceivingThread(MDUser mdUser, Socket sock){
		   this.mdUser = mdUser;
		   this.sock = sock;
	   }
	   
	   public void getShapeObjects(){
		   try {
			   ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
			   mdUser.ShapeObjects = (LinkedList<ShapeObject>)ois.readObject();
			   mdUser.md.refreshShapeObjects();
		   } catch (IOException e) {
			   e.printStackTrace();
		   } catch (ClassNotFoundException e) {
			   e.printStackTrace();
		   }
	   }
       public synchronized void run() 
       {
           Scanner remoteIn = null;
           try 
           {  
        	 getShapeObjects();
        	 remoteIn = new Scanner(sock.getInputStream());
             while (remoteIn.hasNextLine()){
                 String s = remoteIn.nextLine();
                 if(s.contains("<<REFSHAPEOBJS>>")){
                	 getShapeObjects();
                	 mdUser.md.canvas.getCurrentTool().paintObjects(1);
                 }else if(s.contains("<<READY>>")){
                	 mdUser.sendShapeObjects();
                 }else if(s.contains("<<GOTEM>>")){
                	 mdUser.remoteOut.println("<<REF>>");
                 }else if(s.contains("<<USRMSG>>")){
                	 mdUser.serverText.append(s.replace("<<USRMSG>>","") + "\n");
                	 mdUser.serverText.setCaretPosition(mdUser.serverText.getText().length()-1);
                 }
                 //mdUser.message.requestFocus();  
             }
           }
           catch (IOException e){ 
        	   System.out.println(e.getMessage() + ": Connection to peer lost."); 
           } 
           finally 
           {  
              if (remoteIn != null) remoteIn.close(); 
           }
       }
   }